#!/home/rebeater/Miniconda/envs/navigation/bin/python
# -*- coding:utf-8 -*-
# @Time : 4/6/22 11:00 PM
# @Author :  rebeater
# @File : demo.py
# @Project:  NavigationTool_qt
# @Function: Read and show pig file, whitch is saved by matplotlib

import matplotlib.pyplot as plt
import pickle
import sys
import os
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from ui_PigViewer import Ui_MainWindow


def show(path: str):
    with open(path, 'rb') as f:
        try:
            fig = pickle.load(f)
            plt.show()
        except Exception as e:
            print(e.args[0])


class PigViewerWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, path: str):
        super(PigViewerWindow, self).__init__()
        self.setupUi(self)
        self.setAcceptDrops(True)
        self.path = path
        # self.pushButton.setText(path)

    def showInfo(self, info: str) -> None:
        self.label.setText(info)

    def showPig(self, path) -> None:
        print("showPig")
        with open(path, 'rb') as f:
            try:
                fig = pickle.load(f)
                if not isinstance(fig, plt.Figure):
                    self.showInfo("Wrong format")
                else:
                    fig.show()
            except pickle.PickleError as e:
                self.showInfo("Wrong format")

    def dragEnterEvent(self, a0: QtGui.QDragEnterEvent) -> None:
        a0.accept()

    def dropEvent(self, a0: QtGui.QDropEvent) -> None:
        print("dropEvent")
        if a0.mimeData().hasUrls():
            path = a0.mimeData().urls()[0].toLocalFile()
            self.path = path
            if os.path.exists(self.path):
                self.showPig(self.path)
            else:
                self.showInfo("%s is not a file " % self.path)
        self.path = None
        a0.accept()


if __name__ == '__main__':
    # path = "demo.pig"
    # save_demo_fig(path)
    # exit()
    if len(sys.argv) > 1 and os.path.exists(sys.argv[0]):
        path = sys.argv[1]
        print("load", path)
        show(path)
    else:
        app = QApplication(sys.argv)
        w = PigViewerWindow(str(sys.argv))
        w.show()
        sys.exit(app.exec_())
